var BigScreen = (function ($) {
    var switchdata = {}, firewalldata = {};
    var geoMapChart = echarts.init(document.getElementById('deviceMap'));
    var URL = {
        "getNetworkGeoMap": contextPath + "/assetNetworkScreen/getNetworkGeoMap?code=",
        "getNetworkSummary": contextPath + "/assetNetworkScreen/getNetworkSummary?code=",
        "getNetworkTypeSummary": contextPath + "/assetNetworkScreen/getNetworkTypeSummary?code=",
        "getCodeName": contextPath + "/assetNetworkScreen/getCodeName?code=",
    }
    var globalCode = code;

    function generatePaginatedHTML(data) {
        const itemsPerPage = 6;
        const pages = [];
        for (let i = 0; i < data.length; i += itemsPerPage) {
            const pageItems = data.slice(i, i + itemsPerPage);
            pages.push(pageItems);
        }

        let tableHtmlStr = '';

        pages.forEach(function (page, pageIndex) {
            let pageHtmlStr = '';

            page.forEach(function (item, index) {
                let name = item.name;
                let totalCount = item.totalCount;
                let onlineCount = item.onlineCount;
                let onlineRate = Math.round(item.onlineRate);
                let displayIndex = (pageIndex * itemsPerPage) + index + 1;

                pageHtmlStr += `<div style="border-bottom:1px solid #2bede657;display:flex;justify-content: space-between;text-align: center;padding: 4% 0;color:#03A1D6;">
                <div style="width:25%">${displayIndex}.${name}</div>
                <div style="width:25%">${totalCount}</div>
                <div style="width:25%">${onlineCount}</div>
                <div style="width:25%">${onlineRate}%</div>
            </div>`;
            });

            tableHtmlStr += `<div class="swiper-slide">${pageHtmlStr}</div>`;
        });
        return `${tableHtmlStr}`;
    }

    function calculatePercentageValues(typedatas) {
        const totalCount = typedatas.value.reduce((sum, value) => sum + value, 0);

        if (totalCount === 0) {
            typedatas.value = Array(typedatas.name.length).fill(0);
        } else {
            typedatas.value = typedatas.value.map((value) =>
                Math.round((value / totalCount) * 100)
            );
        }

        return typedatas;
    }

    function changeState(param) {
        return;
        if ($(param).css('boxShadow') == 'none') {
            $(param).css({color: 'yellow', border: '0px solid', 'boxShadow': '0 0 10px yellow'})
            $(param + ' span').css({color: 'yellow'});
// 获取值
            var values = $(param + ' span').html()
        } else {
            $(param).css({color: '', border: 0, 'boxShadow': 'none'})
            $(param + ' span').css({color: '#03A1D6'})
        }
    }

    function init(params) {
        let swiper = new Swiper(".mySwiper", {
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
        });
        // 渲染左侧的结构
        $.ajax({
            url: URL.getNetworkSummary + params,
            method: 'POST',
            dataType: 'json',
            async: true, // 设置为异步请求
            success: function (data) {

                $('.total-count').text(data.totalCount || 0);
                $('.total-abnormal-count').text(data.activeCount || 0);
                $('.total-online-count').text(data.onlineCount || 0);
                let datas = {
                    name: [],
                    value: []
                };
                let count = 0;
                data.data.forEach(function (item, index) {
                    if (count < 10) {
                        let name = item.name;
                        let onlineRate = Math.round(item.onlineRate);
                        datas.name.push(name);
                        datas.value.push(onlineRate);
                        count++;
                    }
                });
                const paginatedHTML = generatePaginatedHTML(data.data);
                $(".network-tab-content").html(paginatedHTML);
                initOnlineRateEcharts(datas);
            }
        });

        // 渲染右侧的数据
        $.ajax({
            url: URL.getNetworkTypeSummary + params,
            method: 'POST',
            dataType: 'json',
            async: true, // 设置为异步请求
            success: function (data) {
                switchdata = data['switch'];
                firewalldata = data['firewall'];
                changeTab(1);
            }
        });

        let jsonDataUrl = contextPath + "/page/adminSystem/index/bigScreen/navigation/two/json/" + params + ".json";
        //获取地图
        $.getJSON(jsonDataUrl, function (geoJson) {
            echarts.registerMap(params, geoJson);
            // 渲染中间的地图
            $.ajax({
                url: URL.getNetworkGeoMap + params,
                method: 'POST',
                dataType: 'json',
                async: true, // 设置为异步请求
                success: function (data) {
                    initCenterGeoMap(data.geoCoordMap, data.dataList, data.moveLineList, params)
                }
            });

        });


    }

    /**
     * 初始化左侧在线率echarts图表
     * @param param
     */
    function initOnlineRateEcharts(param) {
        // 基于准备好的dom，初始化echarts实例
        let myChart = echarts.init(document.getElementById('deviceCPU'));
        // 绘制图表
        myChart.setOption({
            title: {
                text: '在线率TOP10',
                textStyle: {
                    fontSize: '12px',
                    color: '#fff'
                },
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                //  formatter: function (params) {
                // 	 var tar = params[0];

                // 	 return tar.name + '<br/>' + tar.seriesName + ' : ' + tar.value + '分';
                //  }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '5%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                splitLine: {
                    show: false //去掉网格线
                },
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: false
                }
                // boundaryGap: [0, 0.01]
            },
            yAxis: [{
                type: 'category',
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },

                axisLabel: {
                    show: true,
                    textStyle: {
                        color: '#fff'
                    },
                    // formatter: function (params) {
                    // 	return params+'%'
                    // }
                },
                data: param['name'],
                // scale : true,
                // splitNumber : 10,
                // boundaryGap : [ 10, 10 ]
            }
            ],
            // barWidth:16,
            // barGap:'-50%',
            series: [
                {
                    name: '在线率',
                    type: 'bar',
                    label: {
                        show: true,
                        formatter: '{c}%',
                        color: '#fff',
                        offset: [10, 0],
                        position: 'inside'
                    },
                    barWidth: 12,
                    barGap: 1,
                    barCategoryGap: 1,
                    //  showBackground: true,
                    itemStyle: {
                        //  color: '#00DEFF',
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            {offset: 0, color: '#ff8c2657'},
                            {offset: 0.5, color: '#ff8c26a3'},
                            {offset: 1, color: '#FFA627'}
                        ]),
                        barBorderRadius: 10,

                    },
                    // showBackground: true,
                    // backgroundStyle: {
                    //         color: 'rgba(180, 180, 180, 0.2)',
                    //     },
                    data: param['value'].reverse(),
                    emphasis: {
                        itemStyle: {
                            // shadowColor:'red',
                            // shadowBlur:20
                        }
                    }
                }
            ]
        });
    }


    function changeMap(geoCoordMap, data, moveLine, area) {
        let convertData = function (data) {
            let res = [];
            for (let i = 0; i < data.length; i++) {
                let geoCoord = geoCoordMap[data[i].name];
                if (geoCoord) {
                    res.push({
                        name: data[i].name,
                        value: geoCoord.concat(data[i].value),
                        status: data[i].status,
                        level: data[i].level,
                        id: data[i].id,
                        pid: data[i].pid,
                        ppid: data[i].ppid,
                        province: data[i].province,
                    });
                }
            }
            return res;
        };
        let convertProvinceData = function (data) {
            let resProvince = [];
            for (let i = 0; i < data.length; i++) {
                let geoCoord = geoCoordMap[data[i].name];
                if (geoCoord&& data[i]['province']) {
                    resProvince.push({
                        name: data[i].name,
                        value: geoCoord.concat(data[i].value),
                        status: data[i].status,
                        id: data[i].id
                    });
                }
            }
            return resProvince;
        };

        return {
            tooltip: {
                trigger: 'item',
                formatter: function (params) {
                    if (params['name'] && String(params.value).indexOf(',') > 0) {
                        return params.name + ' : ' + params.value.slice(params.value.length - 1) + '台';
                    } else if (params['name']) {
                        if (isNaN(params.value)){
                            return params.name + ' : ' + 0 + '台';
                        }else {
                            return params.name + ' : ' + params.value + '台';
                        }
                    }
                }
            },
            visualMap: {
                show: false,
                min: 0,
                max: 500,
                left: 'left',
                top: 'bottom',
                text: ['高', '低'], // 文本，默认为数值文本
                calculable: true,
                seriesIndex: [1],
                inRange: {
                    // color: ["#18554A", "#1A5C51", "#1C6557"],
                },
                // inRange: {

                // 	// color: ['#9074c3', '#4487d5', '#7e9e8e', '#51a2c2']

                // }
            },

            geo: {
                show: true,
                map: area,
                // zoom:0.6,
                scaleLimit: {
                    min: 0.5, //缩放最小大小
                    max: 2, //缩放最大大小
                },
                // regions: [{ name: "南海诸岛", value: 0, itemStyle: { normal: { opacity: 0, label: { show: false } } } }],
                label: {
                    normal: {
                        show: false,
                        color:'#fff',
                        // fontSize:'14px'
                    },
                    emphasis: {
                        show: false,
                    }
                },
                roam: false,
                itemStyle: {
                    normal: {
                        areaColor: '#15587e',
                        borderColor: '#fff',
                        borderWidth: 2,
                        shadowColor: 'rgba(63, 218, 255, 0.5)',
                        shadowBlur: 30,
                        opacity:0.6
                    },
                    emphasis: {
                        areaColor: '#2B91B7',
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        }
                    }
                }
            },
            series: [

                {
                    type: 'map',
                    map: area,
                    geoIndex: 0,
                    aspectScale: 0.75, //长宽比
                    showLegendSymbol: false, // 存在legend时显示
                    label: {
                        normal: {
                            show: false
                        },
                        emphasis: {
                            show: false,
                            textStyle: {
                                color: '#fff'
                            }
                        }
                    },
                    roam: false,
                    itemStyle: {
                        normal: {
                            areaColor: '#031525',
                            borderColor: '#FFFFFF',
                        },
                        emphasis: {
                            areaColor: '#2B91B7',
                            label: {
                                show: false
                            },
                            labelLine: {
                                show: false
                            }
                        }
                    },
                    animation: false,
                    data: data
                },
                {
                    name: '省会',
                    type: 'effectScatter',
                    coordinateSystem: 'geo',
                    zlevel: 2,
                    showEffectOn: 'render',
                    symbol: `image://${contextPath}/page/adminSystem/index/bigScreen/navigation/two/img/star.png`,
                    rippleEffect: {
                        // scale: 3,
                        scale: 0,
                        brushType: 'stroke'
                    },
                    hoverAnimation: true,   //鼠标移上去显示数据
                    label: {
                        normal: {
                            show: false,
                            position: 'right',
                            formatter: '{b}',
                        },
                        emphasis: {
                            show: true
                        }
                    },
                    symbolSize: function (val) {
                        return 30;
                    },
                    itemStyle: {
                        normal: {
                            color: '#2BEDE6',//#F4E925
                            shadowBlur: 10,
                            shadowColor: '#05C3F9'
                        }
                    },
                    data: convertProvinceData(data)
                },
                {
                    name: '城市',
                    type: 'effectScatter',
                    coordinateSystem: 'geo',
                    zlevel: 1,
                    showEffectOn: 'render',
                    // symbol:'image://./img/star.png',
                    rippleEffect: {
                        scale: 2,
                        // scale:0,
                        brushType: 'stroke'
                    },
                    hoverAnimation: true,   //鼠标移上去显示数据
                    label: {
                        normal: {
                            show: true,
                            position: 'right',
                            formatter: '{b}',
                        },
                        emphasis: {
                            show: true
                        }
                    },
                    symbolSize: function (val) {
                        if (val[2]===0){
                            return 0;
                        }
                        return 10;
                    },
                    itemStyle: {
                        normal: {
                            color: '#2BEDE6',//#F4E925
                            shadowBlur: 10,
                            shadowColor: '#05C3F9'
                        }
                    },
                    data: convertData(data),
                },

                // 射线样式
                {
                    name: '线路',
                    type: 'lines',
                    coordinateSystem: 'geo',
                    zlevel: 2,  //数值越大越在上面
                    large: true,
                    symbol: ['none', 'arrow'],
                    effect: {
                        show: true,
                        period: 6,
                        constantSpeed: 10,
                        trailLength: 0,
                        symbolSize: 3    //圆点大小
                    },
                    lineStyle: {
                        normal: {
                            // 线条颜色
                            // color: '#0fff17',
                            color: function (params) {
                                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: params['data']['status'] == 1 ? 'green' : (params['data']['status'] == 2 ? 'yellow' : (params['data']['status'] == 3 ? 'red' : ''))
                                }, {
                                    offset: 1,
                                    color: params['data']['status'] == 1 ? 'green' : (params['data']['status'] == 2 ? 'yellow' : (params['data']['status'] == 3 ? 'red' : ''))
                                }], false)
                            },

                            width: 0.5,
                            opacity: 0.6,
                            curveness: 0.2
                        }
                    },
                    data: moveLine
                },
                // 射线样式
                {
                    name: '线路',
                    type: 'lines',
                    coordinateSystem: 'geo',
                    zlevel: 3,
                    large: true,
                    effect: {
                        show: true,
                        period: 2,
                        trailLength: 0.8,   //特效尾迹的长度
                        color: '#fff',
                        symbolSize: 3   //圆点大小
                    },
                    lineStyle: {
                        normal: {
                            // color:'#0fff17',
                            color: function (params) {
                                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                    offset: 0,
                                    color: params['data']['status']==1?'green':(params['data']['status']==2?'yellow': (params['data']['status'] == 3?'red':''))
                                }, {
                                    offset: 1,
                                    color: params['data']['status'] == 1 ? 'green' : (params['data']['status'] == 2 ? 'yellow' : (params['data']['status'] == 3 ? 'red' : ''))
                                }], false)
                            },
                            width: 0.2,
                            curveness: 0.2
                        }
                    },
                    data: moveLine
                }

            ]
        }
    }

    /**
     * 渲染中间的地图
     * @param geoCoordMap
     * @param data
     * @param moveLine
     * @param area
     */
    function initCenterGeoMap(geoCoordMap, data, moveLine, area) {
        // 基于准备好的dom，初始化echarts实例
        geoMapChart.clear();
        geoMapChart.dispose();
        geoMapChart = echarts.init(document.getElementById('deviceMap'));
        let mapOption = changeMap(geoCoordMap, data, moveLine, area);
        // 绘制图表
        geoMapChart.setOption(mapOption, true);
        //点击地图事件
        geoMapChart.off('click');
        geoMapChart.on("dblclick", (params) => {
            let data = params.data;
            if (data && data.level) {
                let level = data.level;
                let id = data.id;
                let ppid = data.ppid;
                if (level === "2") {
                    globalCode = ppid;
                    init(ppid);
                } else if (level === "1" || level === "0") {
                    globalCode = id;
                    init(id);
                } else {
                    globalCode = code;
                    init(code);
                }
            } else {
                globalCode = code;
                init(code);
            }
        });
    }

    /**
     * 渲染右侧的echarts
     * @param param
     */
    function devicetype(param) {
        // 基于准备好的dom，初始化echarts实例
        let myChart = echarts.init(document.getElementById('deviceType'));
        // 绘制图表
        myChart.setOption({
            polar: {
                radius: [30, '80%']
            },
            angleAxis: {
                max: 100,
                // startAngle: 100
            },
            radiusAxis: {
                type: 'category',
                data: param['name']
            },
            tooltip: {},
            series: {
                type: 'bar',
                data: param['value'],
                coordinateSystem: 'polar',
                label: {
                    show: true,
                    position: 'middle',
                    formatter: '{b}: {c}%',
                    textStyle: {
                        color: '#fff'
                    },
                },
                itemStyle: {
                    borderRadius: 8,
                    normal: {
                        color: function (params) {
                            // ['#1f77b4', '#ff7f0e', '#2ca02c']
                            var colorList = [
                                {
                                    c1: '#1f77b4',//正常
                                    c2: '#1f77b4'
                                },
                                {
                                    c1: '#ff7f0e',  //异常
                                    c2: '#ff7f0e'

                                },
                                {
                                    c1: '#2ca02c',  //失联
                                    c2: '#2ca02c'
                                }];
                            return new echarts.graphic.LinearGradient(1, 1, 0, 0, [{ //颜色渐变函数 前四个参数分别表示四个位置依次为左、下、右、上

                                offset: 0,
                                color: colorList[params.dataIndex].c1
                            }, {
                                offset: 1,
                                color: colorList[params.dataIndex].c2
                            }])
                        }
                    }
                },
            },
            legend: {
                show: true,
                orient: 'vertical',
                left: 'left'
                // position: 'left',
                // textStyle: {
                // 	color: '#fff'
                // },
                // data: ['A', 'B', 'C']
            }
        })
    }

    /**
     * 切换右侧的视图
     * @param param 1:交换机 2:防火墙
     */
    function changeTab(param) {
        $('.unnormal').css({'display': param == 2 ? 'none' : 'block'});
        $('.exchange').css(param == 1 ? {
            border: '1px dashed #03A1D6',
            color: '#03A1D6'
        } : {border: '1px dashed #838384', color: '#838384'});
        $('.firewall').css(param == 1 ? {
            border: '1px dashed #838384',
            color: '#838384'
        } : {border: '1px dashed #03A1D6', color: '#03A1D6'});

        let typedatas = {};
        if (param == 1) {
            typedatas = {
                name: ['正常', '异常', '失联'],
                value: [switchdata['normal'], switchdata['abnormal'], switchdata['lossOfConnection']]
            };
            document.getElementById('normalNum').innerHTML = switchdata['normal']
            document.getElementById('unnormalNum').innerHTML = switchdata['abnormal']
            document.getElementById('lossNum').innerHTML = switchdata['lossOfConnection']
        } else {
            typedatas = {
                name: ['正常', '失联'],
                value: [firewalldata['normal'], firewalldata['lossOfConnection']]
            };
            document.getElementById('normalNum').innerHTML = firewalldata['normal']
            document.getElementById('lossNum').innerHTML = firewalldata['lossOfConnection']
        }
        devicetype(calculatePercentageValues(typedatas))

    }

    function getGlobalCode() {
        return globalCode;
    }

    return {
        changeTab: changeTab,
        init: init,
        changeState: changeState,
        getGlobalCode: getGlobalCode,


    };


})(jQuery);
$(function () {
    BigScreen.init(BigScreen.getGlobalCode());
    setInterval(function () {
        BigScreen.init(BigScreen.getGlobalCode())
    }, 20000);
});
